package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private EmpService empService;


    @Override
    public  PageResult getPageResult(ClazzQueryParam clazzQueryParam) {

        Page page = new Page(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        LambdaQueryWrapper<Clazz> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(clazzQueryParam.getName()!=null && clazzQueryParam.getName()!="",Clazz::getName,clazzQueryParam.getName())
                        .between(clazzQueryParam.getBegin()!=null&& clazzQueryParam.getEnd()!=null,Clazz::getEndDate,clazzQueryParam.getBegin(),clazzQueryParam.getEnd());
        page(page,wrapper);
        List<Clazz> clazzs = page.getRecords();
        List<Long> empids = clazzs.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());
        if(!empids.isEmpty()){
            List<Emp> emps = empService.listByIds(empids);
            clazzs.forEach(clazz->{
                emps.forEach(emp->{
                    if(clazz.getMasterId()!=null && clazz.getMasterId().equals(emp.getId())){
                        clazz.setMasterName(emp.getName());
                    }
                });
            });
        }
        return new PageResult<>(page.getTotal(), clazzs);
    }
}


